package com.gao.controller;

import com.gao.domain.User;
import com.gao.util.LoginCacheUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

/**
 * @author 高鹏
 * @time 2020/04/06 12:12:40
 */
@Controller
public class LoginController {

    // 模拟持久化数据
    private static Set<User> dbUsers;

    static {
        dbUsers = new HashSet<>();
        dbUsers.add(new User(1, "foo", "123"));
        dbUsers.add(new User(2, "bar", "123"));
        dbUsers.add(new User(3, "baz", "123"));
    }

    @PostMapping("login")
    public String doLogin(User user, HttpSession session, HttpServletResponse response) {
        String from = (String) session.getAttribute("from");

        // 登录逻辑
        Optional<User> first = dbUsers.stream().filter(dbUser -> dbUser.getUsername().equals(user.getUsername())
                && dbUser.getPassword().equals(user.getPassword())).findFirst();
        if (first.isPresent()) {
            // 登录成功，保存用户登录信息
            String token = UUID.randomUUID().toString();
            LoginCacheUtils.loginUser.put(token, first.get());

            // 将cookie保存在一级域名中，这样所有二级域名就能共享该cookie了
            Cookie cookie = new Cookie("token", token);
            cookie.setDomain("codeshop.com");
            response.addCookie(cookie);

        } else {
            // 登录失败
            session.setAttribute("msg", "用户名或密码错误");
            return "login";
        }

        // 登录成功，就会跳回来时的页面。
        return "redirect:" + from;
    }

    // 暴露一个端点，供其他子系统通过rest来访问
    @GetMapping("login/info")
    @ResponseBody
    public ResponseEntity<User> getUserInfo(String token) {
        System.out.println(token + "!!!!!");
        // 如果token为空，则表示肯定没有登录，
        // 如果token不为空，才给出响应信息
        if (!StringUtils.isEmpty(token)) {
            User user = LoginCacheUtils.loginUser.get(token);
            return ResponseEntity.ok(user);
        } else {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }


    // 登出
    @GetMapping("logout")
    public String logout(@RequestParam(required = false, defaultValue = "") String from,
                         @CookieValue(value = "token", required = false) Cookie cookie, HttpServletResponse response) {
        if (StringUtils.isEmpty(from)) {
            from = "http://www.codeshop.com:9010/view/index";
        }

        if (cookie != null) {
            String token = cookie.getValue();
            if (!StringUtils.isEmpty(token)) {
                // 从第三方缓存中删除用户登录信息
                LoginCacheUtils.loginUser.remove(token);
                // 从客户端删除登录信息
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        return "redirect:" + from;

    }
}
